package edu.cmu.cs.cs214.hw9.client.gui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

import edu.cmu.cs.cs214.hw9.client.controllers.Event;
import edu.cmu.cs.cs214.hw9.client.controllers.FacelookEvent;
/**
 * The initial login screen. 
 */
public class LoginScreen extends FacelookScreen {
	private static final long serialVersionUID = -4003248316920737877L;
	
	/**
	 * Logs a user into the Facelook system. 
	 */
	private class SendLoginInfo implements ActionListener {
		private JTextField emailField;
		private JPasswordField passwordField;
		
		public SendLoginInfo(JTextField emailField, JPasswordField passwordField) {
			this.emailField = emailField;
			this.passwordField = passwordField;
		}
		
		public void actionPerformed(ActionEvent e) {
			String[] params = new String[2];
			params[0] = emailField.getText();
			params[1] = String.valueOf(passwordField.getPassword());
			fireEventOccured(new FacelookEvent(Event.LOGIN, params));
		}
	}
	
	/**
	 * Constructs a login screen.
	 */
	public LoginScreen() {
		// Layout init.
		GridBagConstraints c = new GridBagConstraints();
		
		// Descriptive labels
		JLabel loginLabel = new JLabel("Login to Facelook");
		JLabel emailLabel = new JLabel("Email Address: ");
		JLabel passwordLabel = new JLabel("Password: ");
		
		// Make label font white.
		loginLabel.setForeground(Color.white);
		emailLabel.setForeground(Color.white);
		passwordLabel.setForeground(Color.white);
		
		// Email and password fields.
		JTextField emailField = new JTextField();
		JPasswordField passwordField = new JPasswordField();
		
		// Initialize email and password fields to a reasonable length like ~20 columns.
		emailField.setColumns(30);
		passwordField.setColumns(20);
		
		JButton loginButton = new JButton("Login");
		JButton registerButton = new JButton("Register");
		
		// Register button goes to the registration screen.
		registerButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				fireEventOccured(new FacelookEvent(Event.GO_TO_REGISTRATION, null));
			}
		});
		
		// Login button logs the user in based on the entered email and password.
		loginButton.addActionListener(new SendLoginInfo(emailField, passwordField));
		
		// Add components to the layout.
		
		// 1st Row
		c.gridx = 0;
		c.gridwidth = 2;
		add(loginLabel, c);
		
		// 2nd row
		c.gridx = 0;
		c.gridwidth = 1;
		c.anchor = GridBagConstraints.WEST;
		add(emailLabel, c);
		
		c.gridx = 1;
		add(emailField, c);
		
		// 3rd Row
		c.gridx = 0;
		add(passwordLabel, c);
		
		c.gridx = 1;
		add(passwordField, c);
		
		// 4th Row
		c.anchor = GridBagConstraints.CENTER;
		c.gridx = 0;
		add(loginButton, c);
		
		c.gridx = 1;
		add(registerButton, c);
	}
}
